Hi,
I have a question if there is a way for solving this problem in C.
Given an interface like this:
char * doublestring(char *str);
An implementation requirement that states:
Given an input string "Test " the function doublestring shall return "Test Test" and using only a string that exactly matches the required size (so input string x 2 + 1 as there is a space)and the constraint of not using helper functions (I assume malloc...) is there a way to implement this?
The problem obviously is, that when creating an array in the function like outputString[lengthInput*2+1] it triggers the warning "warning: function returns address of local variable" as the array is removed from stack. When using a global array I cannot make it dynamic as the interface without prior counting the chars in the string until '\0'.
One could like use the argument pointer, but then I am only sure that the amount of size required for the input string (which is smaller than the outputstring) is reserved...
Also I cannot make the array static, as the size can change with every call...
So a dirty "solution" would be
Code:
#include <stdio.h>
#undef DEBUG
char *strdouble(char *str);
int main()
{
char *str = strdouble("This is a test sentence!");
printf ("%s", str);
char *str2 = strdouble("");
printf ("%s", str2);
return 0;
}
char *strdouble(char *str)
{
int lenOfInput = 0U;
// Find out length. String per
// defintion terminated by '\0'
while(str[lenOfInput] != '\0' ) {
++lenOfInput;
}
// Now create the outputstring
int lenOfOutput = lenOfInput * 2 + 1;
int strTwoOffset = lenOfInput + 1;
char outputString[lenOfOutput];
#ifdef DEBUG
printf ("Output %d \n", lenOfOutput);
printf ("Input %d \n", lenOfInput);
#endif
for (int iterator = 0; iterator < lenOfInput; iterator++) {
outputString[iterator] = str[iterator];
outputString[iterator + strTwoOffset] = str[iterator];
}
outputString[lenOfInput] = 0x20;
outputString[lenOfOutput] = '\0';
str = outputString;
return str;
}
But that cant be the way to go...
I really didn't find anything by googling to solve this issue, other than malloc or making things static (which I cant do here).
Is this actually doable?
BR